#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <netinet/in.h>
#define SERVPORT 3333 //定义端口号
#define BACKLOG 10 //请求队列中允许的最大请求数
#define MAXDATASIZE 100 //数据长度

int main() {
    struct sockaddr_in server_sockaddr, client_sockaddr;
    int sin_size, recvbytes;
    int listen_socket_fd, client_socket_fd; 
    char buf[MAXDATASIZE];
	
    if((listen_socket_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
        perror("创建 server socket 失败");
        exit(1);
    }

    printf("Socket success!, listen_socket_fd = %d\n", listen_socket_fd);

	// 发送缓冲区大小
	int snd_buf_size;
	int optlen = sizeof(snd_buf_size);
	getsockopt(listen_socket_fd, SOL_SOCKET, SO_SNDBUF, &snd_buf_size, (socklen_t*)&optlen);
	printf("the default send buffer size is %d\n", snd_buf_size);	
	
	snd_buf_size = 4000;
	setsockopt(listen_socket_fd, SOL_SOCKET, SO_SNDBUF, &snd_buf_size, optlen);
	
	getsockopt(listen_socket_fd, SOL_SOCKET, SO_SNDBUF, &snd_buf_size, (socklen_t*)&optlen);
	printf("the modified send buffer size is %d\n", snd_buf_size);	

	// 接收缓冲区大小
	int rcv_buf_size;
	optlen = sizeof(rcv_buf_size);
	getsockopt(listen_socket_fd, SOL_SOCKET, SO_RCVBUF, &rcv_buf_size, (socklen_t*)&optlen);
	printf("the default receive buffer size is %d\n", rcv_buf_size);	
	
	rcv_buf_size = 2001;
	setsockopt(listen_socket_fd, SOL_SOCKET, SO_RCVBUF, &rcv_buf_size, optlen);
	
	getsockopt(listen_socket_fd, SOL_SOCKET, SO_RCVBUF, &rcv_buf_size, (socklen_t*)&optlen);
	printf("the modified receive buffer size is %d\n", rcv_buf_size);	


    server_sockaddr.sin_family = AF_INET;
    server_sockaddr.sin_port = htons(SERVPORT);
    server_sockaddr.sin_addr.s_addr = INADDR_ANY;
	
    if((bind(listen_socket_fd, (struct sockaddr *)&server_sockaddr, sizeof(struct sockaddr))) == -1) {
        perror("bind");
        exit(-1);
    }

    printf("bind success!\n");
	
    if(listen(listen_socket_fd, BACKLOG) == -1) {
        perror("listen");
        exit(1);
    }

    printf("listening ... \n");
	
    if((client_socket_fd = accept(listen_socket_fd,(struct sockaddr *) &client_sockaddr, &sin_size)) == -1) {
        perror("accept");
        exit(1);
    }

    printf("accept success!\n");

    if((recvbytes = read(client_socket_fd, buf, MAXDATASIZE)) == -1) {
        perror("read");
        exit(1);
    }

    printf("received a connection : %s\n", buf);
	
	close(client_socket_fd);
    close(listen_socket_fd);

}
